package name.wilbur.course.db.bigone.dao.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import name.wilbur.course.db.bigone.dao.BaseDAO;
import name.wilbur.course.db.bigone.model.City;
import name.wilbur.course.db.bigone.util.Checker;



/**
 * @author wilbur
 */
public class CityDAO extends BaseDAO implements ICityDAO {
	public CityDAO() {
		super(City.class);
	}
	
	public int getPkByName(String cityName) {
		int cityID = -1;
		if (Checker.notEmptyString(cityName)) {
			String sql = "SELECT " + primaryKey + " FROM " + table + 
						" WHERE CityName = '" + cityName + "'";
			try {
				queryNotClose(sql);
				if (getResultSet().next())
					cityID = rs.getInt(1);
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				closeConnection();
			}
		}
		return cityID;
	}
	
	/**
	 * @param str null return all cities in a Map<String, String>.
	 */
	public Map<String, String> findCitys(String str) {
		String sql = "SELECT CityID, CityName FROM " + table;
		String sqlCnt = "SELECT COUNT(CityID) FROM " + table;
		Map<String, String> NameID = null;
		try {
			if (str==null) {
				/* get all cities */
				queryNotClose(sqlCnt);
				if (rs.next()) {
					int cnt = rs.getInt(1);
					if (cnt == 0) {
						log.debug("No city available.");
						return null;
					}
					NameID = new HashMap<String, String>(cnt);
				}
				closeConnection();
				queryNotClose(sql);
				while (rs.next()) {
					NameID.put(rs.getString(1), rs.getString(2));
				}
				closeConnection();
			} else {
				/* not implemented now */
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return NameID;
	}
}
